<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hyperf_mall
 * @contact  hyperf_mall@163.com
 */

namespace App\Repository;

use App\Model\ConfigModel;
use Hyperf\Di\Annotation\Inject;

class ConfigRepository extends BaseRepository
{
    /**
     * @Inject
     * @var ConfigModel
     */
    protected $model;

    /**
     * Notes: 获取配置
     * Author: Bruce.z
     * DateTime: 2022/6/10 17:15
     * @param string $key
     * @return mixed|string
     */
    public function getByKey(string $key)
    {
        $row = $this->getOne(['key'=>$key]);
        if($row['value_type'] == 1) return $row['value'];
        elseif ($row['value_type'] == 2) return json_decode($row['value'], true);
        else return '';
    }

    /**
     * Notes: 设置配置项
     * Author: Bruce.z
     * DateTime: 2022/6/10 17:14
     * @param string $key
     * @param $data
     * @return \App\Model\BaseModel|bool|\Hyperf\Database\Model\Model
     */
    public function set(string $key, $data)
    {
        $row = $this->getOne(['key'=>$key]);
        $_data = [];
        $_data['key'] = $key;
        $_data['value_type'] = 1;
        $_data['value'] = $data;
        if(is_array($data)){
            $_data['value_type'] = 2;
            $_data['value'] = json_encode($data);
        }
        if(empty($row)){
            return $this->baseAdd($_data);
        }else{
            return $this->updateByConditions(['key'=>$key], $_data);
        }
    }
}
